package com.example.demo.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


@RestController
public class TestController {



    private static final String APP_ID = "wx04706d94a36bf768";
    private static final String PATH = "/pages/index/index";

    @RequestMapping(value = "/")
    public String test()
    {
        return "hello cc";
    }

    @RequestMapping(value = "/qr")
    public ResponseEntity<byte[]> qrGenerate(String content, HttpServletResponse response) throws IOException {
        try {
            BufferedImage image = QrCodeUtil.generate("", 400, 400);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "png", outputStream);
            return ResponseEntity
                    .status(HttpStatus.OK)
                    .contentType(MediaType.IMAGE_PNG)
                    .body(outputStream.toByteArray());
        } catch (IOException e) {
            // Handle exception appropriately
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }



    }


    @GetMapping(value = "/api/qrcode", produces = MediaType.IMAGE_PNG_VALUE)
    public ResponseEntity<byte[]> generateQrCode(@RequestParam String text, @RequestParam(defaultValue = "200") Integer size) throws Exception {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        QRCodeWriter writer = new QRCodeWriter();
        String fullUrl = String.format("https://servicewechat.com/%s%s?%s", APP_ID, PATH, text);
        BitMatrix matrix = writer.encode(fullUrl, BarcodeFormat.QR_CODE, size, size);
        ImageIO.write(MatrixToImageWriter.toBufferedImage(matrix), "png", stream);
        return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).body(stream.toByteArray());
    }


    @GetMapping("/cc")
    public ResponseEntity<byte[]> generateQRCode() throws IOException, WriterException {
        Map<String, String> params = new HashMap<>();
        String scene = "wxc480c39cb9dd6ebb";
        String page = "pages/contact/contact";
        if (scene != null) {
            params.put("scene", scene);
        }
        if (page != null) {
            params.put("page", page);
        }

        String paramsString = params.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .reduce((a, b) -> a + "&" + b)
                .orElse("");

        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(paramsString, BarcodeFormat.QR_CODE, 430, 430);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", byteArrayOutputStream);

        byte[] imageBytes = byteArrayOutputStream.toByteArray();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG);

        return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
    }

    @RequestMapping(value = "/rr")
    public String testObject(@RequestParam("file") MultipartFile file) throws IOException {
        String secretId = "AKID015Kb4UqFg3HxZAqXMF6z7FGFYtXl8Vg";
        String secretKey = "9KQh5Sju2EQczgVOGykiE8Of1KdutTAu";

        COSCredentials cosCredentials = new BasicCOSCredentials(secretId,secretKey);
        ClientConfig clientConfig = new ClientConfig( new Region("ap-guangzhou"));

        COSClient client = new COSClient(cosCredentials,clientConfig);

        InputStream inputStream = file.getInputStream();

        ObjectMetadata objectMetadata = new ObjectMetadata();

        objectMetadata.setContentLength(file.getSize());

        PutObjectRequest putObjectRequest = new PutObjectRequest("cc-1322096065",file.getOriginalFilename(),inputStream,objectMetadata);
        client.putObject(putObjectRequest);
        URL objectUrl = client.getObjectUrl("cc-1322096065", file.getOriginalFilename());
        return objectUrl.toString();
    }

    public static void main(String[] args) {
        String secretId = "AKID015Kb4UqFg3HxZAqXMF6z7FGFYtXl8Vg";
        String secretKey = "9KQh5Sju2EQczgVOGykiE8Of1KdutTAu";

        COSCredentials cosCredentials = new BasicCOSCredentials(secretId,secretKey);
        ClientConfig clientConfig = new ClientConfig( new Region("ap-guangzhou"));

        COSClient client = new COSClient(cosCredentials,clientConfig);


        String folderName = "cc/ff/hh/";

        client.putObject("cc-1322096065", folderName,"");

    }
}
